import axios from "axios";
import WebSocketClient from "../ws/WebSocket";

function renderByOpenApi(service, renderFunc) {
  axios({ method: service.api.method, url: service.api.url }).then(
    (response) => {
      renderFunc(response.data);
    }
  );
}

export function renderWidgetData(widget, renderFunc) {
  let render = {};
  const service = widget.service;
  if (service.type === 0) {
    renderFunc(widget.data);
  } else if (service.type === 1) {
    renderByOpenApi(service, renderFunc);
    let apiTimer = setInterval(() => {
      renderByOpenApi(service, renderFunc);
    }, service.api.refresh);
    render.apiTimer = apiTimer;
  } else if (service.type === 3) {
    let websocket = new WebSocketClient(widget.id, widget.service.websocket.url, (resp) => {
      renderFunc(JSON.parse(resp.data));
    });
    websocket.init();
    render.websocket = websocket;
  }
  return render;
}